package com.imonsoft.sqm.web.excel.SpecialClaim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.service.business.supplier_quality.SpecialClaimService;
import com.imonsoft.sqm.service.excel.BaseExcel.ExcelService;
import com.imonsoft.sqm.service.excel.SpecialClaimExcel.SpecialClaimExcelService;

@Controller
@RequestMapping("/excel/specialClaimExcel")
public class SpecialClaimExcelController {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private ExcelService excelService;
	@Autowired
	private SpecialClaimExcelService specialClaimExcelService;
	@Autowired
	private SpecialClaimService specialClaimService;
	@RequestMapping(value = "/specialClaimImportUI.do")
	public void specialClaimImportUI(ModelMap model) {
	}
	/**
	 * description Excel模版下载 on 2013-5-30
	 * 
	 * @a uthor zhouwei
	 */
	@RequestMapping(value = "/excelModel.do", method = RequestMethod.POST)
	public void excelModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		excelService.loadExcelModel(request, response, ConstantSqm.EXCEL_SPECIAL_CLAIM);
	}
	/**
	 * description Excel导入操作 on 2013-5-14
	 * 
	 * @author zhouwei
	 */
	@RequestMapping(value = "/excelUpload.do", method = RequestMethod.POST)
	public void excelUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response,HttpServletRequest request) throws Exception {
		int maxSize = 200;
		int startRow=2;
		ReturnMessage message = new ReturnMessage();
		String result = "<script type=\"text/javascript\">" + "window.parent.OnUploadCompleted('#reslut#');</script>";
		List<Object[]> contentList = null;
		try {
			contentList = excelService.readExcel(file.getInputStream(),maxSize,startRow);
			Map<String, Object> map = new HashMap<String, Object>();
			List<SpecialClaimImportDto> importList = new ArrayList<SpecialClaimImportDto>();
			List<SpecialClaimImportDto> footerRow = new ArrayList<SpecialClaimImportDto>();
			SpecialClaimImportDto footer = new SpecialClaimImportDto();
			List<SpecialClaimImportDto> errorImportList = new ArrayList<SpecialClaimImportDto>();
			List<String> errors = new ArrayList<String>();
			for (Object[] items : contentList) {
				SpecialClaimImportDto dto = new SpecialClaimImportDto();
				dto.setRow(Integer.parseInt(StringUtil.fixup(items[0])));
				dto.setSupplierCode((String) items[1]);// 供应商代码
				dto.setYear((String) items[2]);//月份
				dto.setiFirstJanuary((String)items[3]);
				dto.setiSecondJanuary((String)items[4]);
				dto.setiThirdJanuary((String)items[5]);
				dto.setiFourthJanuary((String)items[6]);
				dto.setiFirstFebruary((String)items[7]);
				dto.setiSecondFebruary((String)items[8]);
				dto.setiThirdFebruary((String)items[9]);
				dto.setiFourthFebruary((String)items[10]);
				dto.setiFirstMarch((String)items[11]);
				dto.setiSecondMarch((String)items[12]);
				dto.setiThirdMarch((String)items[13]);
				dto.setiFourthMarch((String)items[14]);
				dto.setiFirstApril((String)items[15]);
				dto.setiSecondApril((String)items[16]);
				dto.setiThirdApril((String)items[17]);
				dto.setiFourthApril((String)items[18]);
				dto.setiFirstMay((String)items[19]);
				dto.setiSecondMay((String)items[20]);
				dto.setiThirdMay((String)items[21]);
				dto.setiFourthMay((String)items[22]);
				dto.setiFirstJune((String)items[23]);
				dto.setiSecondJune((String)items[24]);
				dto.setiThirdJune((String)items[25]);
				dto.setiFourthJune((String)items[26]);
				dto.setiFirstJuly((String)items[27]);
				dto.setiSecondJuly((String)items[28]);
				dto.setiThirdJuly((String)items[29]);
				dto.setiFourthJuly((String)items[30]);
				dto.setiFirstAugust((String)items[31]);
				dto.setiSecondAugust((String)items[32]);
				dto.setiThirdAugust((String)items[33]);
				dto.setiFourthAugust((String)items[34]);
				dto.setiFirstSeptember((String)items[35]);
				dto.setiSecondSeptember((String)items[36]);
				dto.setiThirdSeptember((String)items[37]);
				dto.setiFourthSeptember((String)items[38]);
				dto.setiFirstOctober((String)items[39]);
				dto.setiSecondOctober((String)items[40]);
				dto.setiThirdOctober((String)items[41]);
				dto.setiFourthOctober((String)items[42]);
				dto.setiFirstNovember((String)items[43]);
				dto.setiSecondNovember((String)items[44]);
				dto.setiThirdNovember((String)items[45]);
				dto.setiFourthNovember((String)items[46]);
				dto.setiFirstDecember((String)items[47]);
				dto.setiSecondDecember((String)items[48]);
				dto.setiThirdDecember((String)items[49]);
				dto.setiFourthDecember((String)items[50]);
				List<String> messages = specialClaimExcelService.txCheckData(dto);
				dto.setHasError(messages.size() > 0);
				importList.add(dto);
				if (dto.isHasError()) {
					errorImportList.add(dto);
				}
				if (errorImportList.size() > maxSize) {
					break;
				}
				errors.addAll(messages);
			}
			footer.setRow(contentList.size());
			footerRow.add(footer);
			map.put("footer", footerRow);
			if (0 == errors.size()) {
				request.getSession().setAttribute(ConstantSqm.SPECIAL_CLAIM_EXCEL_IMPORT, importList);
			}
			if (contentList.size() <= maxSize) {
				map.put("details", importList);
				if (errors.size() == 0&&contentList.size()>0) {
					message.setMsg("数据检查成功。");
				} else if(errors.size() == 0&&contentList.size()<=0){
					map.put("errors", errors);
					message.setMsg("数据检查失败，数据为空。");
				}else{
					map.put("errors", errors);
					message.setMsg("数据检查失败，请查看错误信息。");
				}
			} else {
				if (errors.size() == 0) {
					map.put("details", importList.subList(0, maxSize));
					message.setMsg("数据检查成功，列表中仅显示前500行，更多数据请查看Excel文件。");
				} else {
					if (errorImportList.size() > maxSize) {
						map.put("details", errorImportList.subList(0, errorImportList.size() - 1));
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于错误数据太多，列表中仅显示前500行错误，请仔细检查Excel文件。");
					} else {
						map.put("details", errorImportList);
						map.put("errors", errors);
						message.setMsg("数据检查失败，由于数据量太大，列表中仅显示错误行。");
					}
				}
			}
			message.setObj(map);
			message.setSuccess(true);
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderHTML(response, result.replaceFirst("#reslut#", JsonUtil.bean2json(message)));
	}
	/**
	 * 保存方法
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ajaxSave.do", method = RequestMethod.POST)
	public void ajaxSave(HttpServletRequest request, HttpServletResponse response) {
		ReturnMessage message = new ReturnMessage();
		try {
			@SuppressWarnings("unchecked")
			List<SpecialClaimImportDto> importList = (List<SpecialClaimImportDto>) request.getSession().getAttribute(ConstantSqm.SPECIAL_CLAIM_EXCEL_IMPORT);
			specialClaimService.txInsertForSys(importList);
			request.getSession().removeAttribute(ConstantSqm.SPECIAL_CLAIM_EXCEL_IMPORT);
			message.setSuccess(true);
		}  catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}
}
